﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Traceability.Api.Applications.Permissionts;
using Traceability.Api.Applications.Roless;
using Traceability.Api.Applications.Userss;
using Traceability.Api.Commonts;
using Traceability.Commont.Domains;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.UsersFile;

namespace Traceability.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
   // [Authorize]
    public class TraceController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<TraceController> logger;
        private readonly IConfiguration _configuration;

        public TraceController(IMediator mediator, ILogger<TraceController> logger, IConfiguration configuration)
        {
            this.mediator = mediator;
            this.logger = logger;
            _configuration = configuration;
        }
        /// <summary>
        /// 权限添加1
        /// </summary>
        /// <param name="info">权限实体</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddPermissions(PermissionsCreateCommand info)
        {
            var cou = await mediator.Send(info);
            return cou;
        }
        /// <summary>
        /// 权限级联2
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Resqults<CardsDTo>> GetResqults()
        {
            try
            {
                logger.LogInformation("权限级联");
                var res = await mediator.Send(new PermissionsCartsCommand());
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="info">权限实体</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Resqults<Permissions>> GetPermissions(string? info)
        {
            try
            {
                var list = await mediator.Send(new PermissionsListCommand() { permissName = info });
                return list;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="info">角色DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Resqults> AddRoles(RolesCreateCommand info)
        {
            try
            {
                var res = await mediator.Send(info);
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="rolesName">角色名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Resqults<RolesListDTO>> GetRoles(string? rolesName)
        {
            try
            {
                var res = await mediator.Send(new RolesListCommand() { RolesName = rolesName });
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="info">用户DTO</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Resqults> AddUser(UserCreateCommand infos)
        {
            try
            {
                var res = await mediator.Send(infos);
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pageIndex">当前索引页</param>
        /// <param name="pageSize">每页显示数量</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageDTO<UserListDTO>> getUserList(UserListCommand info)
        {
            try
            {
                var res = await mediator.Send(info);
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<Resqults>  UserLogin(UserLoginCommand info)
        {
            try
            {
                var cou=await mediator.Send(info);
                if (cou.Date!=null )
                {
                    cou.Messges = CreateTokenString();
                }
                return cou;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file">图片</param>
        /// <returns></returns>
        [HttpPost]
        public string Uploat(IFormFile file)
        {
            try
            {
                var fileName = file.FileName;
                var path=Directory.GetCurrentDirectory()+@"\\wwwroot\\Images\\"+fileName;
                using (var fs = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(fs);
                };
                var url = "http://localhost:5021//Images/"+ fileName;
                return url;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 生成 JWT Token（令牌
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            var jwtSettings = _configuration.GetSection("JWT").Get<JWTfiles>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
         new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
         new Claim("Email","pmandy@163.com"),
         new Claim("Phone","123456"),
         new Claim("UserId","1"),
     };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
        /// <summary>
        /// 获取URL
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Resqults<Permissions>>  GetURL(int userId)
        {
            var list =await mediator.Send(new UsaerURLCommand() { UserId = userId });
            return list;
        }
    }
}
